<?php
class ProjectFund extends AppModel
{
    public $name = 'ProjectFund';
    public $actsAs = array(
        'Aggregatable',
        'Logable' => array(
            'userModel' => 'User',
            'userKey' => 'user_id'
        )
    );
    //$validate set in __construct for multi-language support
    //The Associations below have been created with all possible keys, those that are not needed can be removed
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => true,
            'counterScope' => array(
                'OR' => array(
                    array(
                        'is_paid' => 1
                    ) ,
                    array(
                        'is_paid' => 0
                    )
                ) ,
            )
        ) ,
        'Project' => array(
            'className' => 'Project',
            'foreignKey' => 'project_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => false,
        ) ,
        'ProjectReward' => array(
            'className' => 'ProjectReward',
            'foreignKey' => 'project_reward_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'counterCache' => true,
            'counterScope' => array(
                'OR' => array(
                    array(
                        'is_paid' => 1
                    ) ,
                    array(
                        'is_paid' => 0
                    )
                ) ,
                'is_cancelled' => 0,
                'is_refunded' => 0,
            )
        ) ,
        'UserPaypalConnection' => array(
            'className' => 'UserPaypalConnection',
            'foreignKey' => 'user_paypal_connection_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
        )
    );
    public $hasMany = array(
        'Activity' => array(
            'className' => 'Activity',
            'foreignKey' => 'model_id',
            'dependent' => true,
            'conditions' => array(
                'Activity.model' => 'ProjectFund'
            ) ,
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ) ,
        'Transaction' => array(
            'className' => 'Transaction',
            'foreignKey' => 'foreign_id',
            'dependent' => true,
            'conditions' => array(
                'Transaction.class' => 'ProjectFund'
            ) ,
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );
    function __construct($id = false, $table = null, $ds = null)
    {
        parent::__construct($id, $table, $ds);
        $this->validate = array(
            'amount' => array(
                'rule5' => array(
                    'rule' => '_checkForRewardAmount',
                    'allowEmpty' => false,
                    'message' => '',
                ) ,
                'rule4' => array(
                    'rule' => '_checkForReward',
                    'allowEmpty' => false,
                    'message' => __l('You cannot select this reward for the amount you entered.')
                ) ,
                'rule3' => array(
                    'rule' => array(
                        'comparison',
                        '>=',
                        1
                    ) ,
                    'allowEmpty' => false,
                    'message' => __l('Must be greater than zero')
                ) ,
                'rule2' => array(
                    'rule' => '/^[-+]?\\b[0-9]*\\.?[0-9]+\\b$/',
                    'allowEmpty' => false,
                    'message' => __l('Enter only numeric value')
                ) ,
                'rule1' => array(
                    'rule' => 'notempty',
                    'allowEmpty' => false,
                    'message' => __l('Required')
                ) ,
            ) ,
            'project_reward_id' => array(
                'rule1' => array(
                    'rule' => '_checkSoldOutReward',
                    'allowEmpty' => false,
                    'message' => __l('The reward you selected is sold out. Please select some other rewards.')
                ) ,
                'rule1' => array(
                    'rule' => 'notempty',
                    'allowEmpty' => false,
                    'message' => __l('Required')
                ) ,
            ) ,
        );
    }
    function _checkForRewardAmount()
    {
        $project = $this->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $this->data['ProjectFund']['project_id']
            ) ,
            'fields' => array(
                'Project.needed_amount',
                'Project.collected_amount',
                'Project.min_amount_to_fund',
                'Project.pledge_type_id',
                'Project.is_allow_over_funding',
            ) ,
            'recursive' => - 1
        ));
        if (($this->data['ProjectFund']['amount'] > $project['Project']['needed_amount'] - $project['Project']['collected_amount']) && !($project['Project']['is_allow_over_funding'])) {
            $this->validationErrors['amount'] = __l('The amount should be less than needed amount.');
            return true;
        } else if (!empty($project['Project']['pledge_type_id']) && !empty($project['Project']['min_amount_to_fund'])) {
            if ($project['Project']['needed_amount'] % $this->data['ProjectFund']['amount'] != 0 && $project['Project']['pledge_type_id'] == ConstPledgeTypes::Multiple) {
                $this->validationErrors['amount'] = __l('Amount should be multiple of'.$project['Project']['min_amount_to_fund'].".");
                return true;
            } else if ($project['Project']['min_amount_to_fund'] > $this->data['ProjectFund']['amount'] && ($project['Project']['pledge_type_id'] == ConstPledgeTypes::Minimum)) {
                $this->validationErrors['amount'] = __l('The amount should not be less than ') . Configure::read('site.currency') . $project['Project']['min_amount_to_fund'];
                return true;
            } else if ($project['Project']['min_amount_to_fund'] != $this->data['ProjectFund']['amount'] && ($project['Project']['pledge_type_id'] == ConstPledgeTypes::Fixed)) {
                $this->validationErrors['amount'] = __l('The amount should be equal to ') . Configure::read('site.currency') . $project['Project']['min_amount_to_fund'];
                return true;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
    function _checkForReward()
    {
        $projectReward = $this->Project->ProjectReward->find('first', array(
            'conditions' => array(
                'ProjectReward.id' => $this->data['ProjectFund']['project_reward_id']
            ) ,
            'fields' => array(
                'ProjectReward.pledge_amount',
                'ProjectReward.project_id',
            ) ,
            'recursive' => - 1
        ));
        if (!empty($projectReward) && ($this->data['ProjectFund']['project_id'] != $projectReward['ProjectReward']['project_id'] || $this->data['ProjectFund']['amount'] < $projectReward['ProjectReward']['pledge_amount'])) {
            return false;
        }
        return true;
    }
    function _checkSoldOutReward()
    {
        $projectReward = $this->Project->ProjectReward->find('first', array(
            'conditions' => array(
                'ProjectReward.id' => $this->data['ProjectFund']['project_reward_id']
            ) ,
            'fields' => array(
                'ProjectReward.project_fund_count',
                'ProjectReward.pledge_max_user_limit'
            ) ,
            'recursive' => - 1
        ));
        if ($projectReward['ProjectReward']['pledge_max_user_limit'] != 0) {
            if ($projectReward['ProjectReward']['project_fund_count'] >= $projectReward['ProjectReward']['pledge_max_user_limit']) {
                return false;
            }
        }
        return true;
    }
    function afterSave($created)
    {
        $this->Behaviors->detach('Logable');
        $projectFundcount = $this->find('count', array(
            'conditions' => array(
                'OR' => array(
                    array(
                        'ProjectFund.is_paid' => 1
                    ) ,
                    array(
                        'ProjectFund.is_paid' => 0
                    ) ,
                ) ,
                'ProjectFund.project_id' => $this->data['ProjectFund']['project_id'],
                'ProjectFund.is_cancelled' => 0,
                'ProjectFund.is_refunded' => 0
            ) ,
            'recursive' => - 1
        ));
        $updates['Project.project_fund_count'] = $projectFundcount;
        $this->Project->updateAll($updates, array(
            'Project.id' => $this->data['ProjectFund']['project_id']
        ));
        $userFundcount = $this->find('all', array(
            'conditions' => array(
                'OR' => array(
                    array(
                        'ProjectFund.is_paid' => 1
                    ) ,
                    array(
                        'ProjectFund.is_paid' => 0
                    ) ,
                ) ,
                'ProjectFund.user_id' => $this->data['ProjectFund']['user_id'],
                'ProjectFund.is_cancelled' => 0,
                'ProjectFund.is_refunded' => 0,
                'ProjectFund.is_failed' => 0
            ) ,
            'group' => 'ProjectFund.project_id',
            'recursive' => - 1
        ));
        $userupdates['User.unique_project_fund_count'] = count($userFundcount);
        $this->User->updateAll($userupdates, array(
            'User.id' => $this->data['ProjectFund']['user_id']
        ));
    }
}
?>